package com.cherry.sdk.http

import com.cherry.sdk.http.json.Json
import com.cherry.sdk.http.response.ResponseConfig
import com.cherry.sdk.http.token.TokenConverterFactory
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * @author 董棉生(dongmiansheng@parkingwang.com)
 * @since 18-11-16
 */

object NetworkSDK {


    fun init(networkConfig: NetworkConfig, responseConfig: ResponseConfig) {

        val clientBuilder = OkHttpClient.Builder()
                .connectTimeout(networkConfig.connectTimeoutSeconds, TimeUnit.SECONDS)
                .readTimeout(networkConfig.readTimeoutSeconds, TimeUnit.SECONDS)
                .writeTimeout(networkConfig.writeTimeoutSeconds, TimeUnit.SECONDS)

        clientBuilder.addInterceptor { chain ->
            val request = chain.request()
            val requestBuilder = chain.request().newBuilder()
            networkConfig.requestHeaderMap.let {
                if (it.isNotEmpty()) {
                    for (item in it) {
                        requestBuilder.addHeader(item.key, item.value)
                    }
                }
            }

            val token = networkConfig.tokenConfig.tokenProvider.getToken()
            if ("GET".equals(request.method(), ignoreCase = true) && token.isNotEmpty()) {
                requestBuilder.url(request.url()
                        .newBuilder()
                        .addQueryParameter(networkConfig.tokenConfig.tokenKey, token)
                        .build())
            }
            chain.proceed(requestBuilder.build())
        }

        //添加默认的日志打印拦截器


        networkConfig.interceptors.forEach {
            clientBuilder.addInterceptor(it)
        }

        val gson = Json.init(responseConfig).GSON

        if (responseConfig.gsonConverterFactory == null) {
            responseConfig.gsonConverterFactory = GsonConverterFactory.create(gson)
        }

        val retrofit = Retrofit.Builder()
                .addConverterFactory(TokenConverterFactory.create(networkConfig.tokenConfig, gson))
                .addConverterFactory(responseConfig.gsonConverterFactory!!)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(networkConfig.baseUrl)
                .client(clientBuilder.build())
                .build()
        ApiService.setRetrofit(retrofit)
    }

}